{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "b739c0e2",
   "metadata": {},
   "source": [
    "# Image Detection Demo with PytorchWildlife"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1197e180",
   "metadata": {},
   "source": [
    "This tutorial guides you on how to use PyTorchWildlife for image detection. We will go through the process of setting up the environment, defining the detection model, as well as performing inference and saving the results in different ways.\n",
    "\n",
    "## Prerequisites\n",
    "Install PytorchWildlife running the following commands:\n",
    "```bash\n",
    "conda create -n pytorch_wildlife python=3.10 -y\n",
    "conda activate pytorch_wildlife\n",
    "pip install PytorchWildlife\n",
    "```\n",
    "Also, make sure you have a CUDA-capable GPU if you intend to run the model on a GPU. This notebook can also run on CPU.\n",
    "\n",
    "## Importing libraries\n",
    "First, we'll start by importing the necessary libraries and modules."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c44e7713",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import torch\n",
    "from PytorchWildlife.models import detection as pw_detection\n",
    "from PytorchWildlife import utils as pw_utils"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6abd07b5",
   "metadata": {},
   "source": [
    "## Model Initialization\n",
    "We will initialize the MegaDetectorV6 model for image detection. This model is designed for detecting animals in images."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eb25db43",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Setting the device to use for computations ('cuda' indicates GPU)\n",
    "DEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
    "if DEVICE == \"cuda\":\n",
    "    torch.cuda.set_device(0)\n",
    "    \n",
    "# Initializing the MegaDetectorV6 model for image detection\n",
    "# Valid versions are MDV6-yolov9-c, MDV6-yolov9-e, MDV6-yolov10-c, MDV6-yolov10-e or MDV6-rtdetr-c\n",
    "detection_model = pw_detection.MegaDetectorV6(device=DEVICE, pretrained=True, version=\"MDV6-yolov10-e\")\n",
    "\n",
    "# Uncomment the following line to use MegaDetectorV5 instead of MegaDetectorV6\n",
    "#detection_model = pw_detection.MegaDetectorV5(device=DEVICE, pretrained=True, version=\"a\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "64c19af9",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "1e57dcca",
   "metadata": {},
   "source": [
    "## Single Image Detection\n",
    "We will first perform detection on a single image. Make sure to verify that you have the image in the specified path."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0d730b20",
   "metadata": {},
   "outputs": [],
   "source": [
    "tgt_img_path = os.path.join(\".\",\"demo_data\",\"imgs\",\"10050028_0.JPG\")\n",
    "results = detection_model.single_image_detection(tgt_img_path)\n",
    "pw_utils.save_detection_images(results, os.path.join(\".\",\"demo_output\"), overwrite=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2e23329c",
   "metadata": {},
   "source": [
    "## Batch Image Detection\n",
    "Next, we'll demonstrate how to process multiple images in batches. This is useful when you have a large number of images and want to process them efficiently."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "561eff0c",
   "metadata": {},
   "outputs": [],
   "source": [
    "tgt_folder_path = os.path.join(\".\",\"demo_data\",\"imgs\")\n",
    "results = detection_model.batch_image_detection(tgt_folder_path, batch_size=16)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bb41830b",
   "metadata": {},
   "source": [
    "## Output Results\n",
    "PytorchWildlife allows to output detection results in multiple formats. Here are the examples:\n",
    "\n",
    "### 1. Annotated Images:\n",
    "This will output the images with bounding boxes drawn around the detected animals. The images will be saved in the specified output directory."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f63310ab",
   "metadata": {},
   "outputs": [],
   "source": [
    "pw_utils.save_detection_images(results, \"batch_output\", overwrite=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bbd016ae",
   "metadata": {},
   "source": [
    "### 2. Cropped Images:\n",
    "This will output the cropped images of the detected animals. The cropping is done around the detection bounding box, The images will be saved in the specified output directory."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "13653739",
   "metadata": {},
   "outputs": [],
   "source": [
    "pw_utils.save_crop_images(results, \"crop_output\", overwrite=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "49be4063",
   "metadata": {},
   "source": [
    "### 3. JSON Format:\n",
    "This will output the detection results in JSON format. The JSON file will be saved in the specified output directory."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b627280b",
   "metadata": {},
   "outputs": [],
   "source": [
    "pw_utils.save_detection_json(results, os.path.join(\".\",\"batch_output.json\"),\n",
    "                             categories=detection_model.CLASS_NAMES,\n",
    "                             exclude_category_ids=[], # Category IDs can be found in the definition of each model.\n",
    "                             exclude_file_path=None)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fceda190",
   "metadata": {},
   "source": [
    "### 3.1 Timelapse JSON Format:\n",
    "PytorchWildlife is compatible with Timelapse, a popular tool to visualize and process camera trap data. This code will output the detection results in a JSON format compatible with Timelapse:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f2ac9b72",
   "metadata": {},
   "outputs": [],
   "source": [
    "pw_utils.save_detection_timelapse_json(results, os.path.join(\".\",\"batch_output_timelapse.json\"),\n",
    "                                       categories=detection_model.CLASS_NAMES,\n",
    "                                       exclude_category_ids=[], # Category IDs can be found in the definition of each model.\n",
    "                                       exclude_file_path=tgt_folder_path,\n",
    "                                       info={\"detector\": \"MegaDetectorV6\"})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a4ee1d7b",
   "metadata": {},
   "source": [
    "### Copyright (c) Microsoft Corporation. All rights reserved.\n",
    "### Licensed under the MIT License."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "pytorch-wildlife",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.19"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
